<template>
  <q-page class="excel-content-container" style="min-height: 80vh">
    <div class="row" style="width: 20vw" v-if="props.isShowData">
      <!-- 第1列 -->
      <q-card
        class="col-3 left-card tj-padding-sm"
        style="width: 100%; position: relative"
      >
        <div class="centered tj-text-md">dataset1</div>
        <q-card-section class="q-card-section-customize">
          <q-list bordered @dragover.prevent>
            <div
              class="tj-flex tj-flex-row-between tj-padding-xs tj-text-center"
              style="background-color: #ccc; font-size: 12px;"
            >
              <div style="width: 8%">选择</div>
              <div style="width: 18%">变量名</div>
              <div style="width: 18%">变量类型</div>
              <div style="width: 18%">变量标签</div>
              <div style="width: 18%">变量赋值</div>
            </div>

            <!-- 数据集表头展示部分 -->
            <q-item
              v-for="(item, index) in remainingItems"
              :key="index"
              clickable
              tag="div"
              v-ripple
              class="draggable-item"
              :class="{ 'is-dragging': isDraggingItem === index }"
              :draggable="index === 0 || item.isSelected"
              @dragstart="onDragStart(item, index, 'remainingItems')"
              @dragend="onDragEnd"
              @dragover.prevent
              @dragenter="onDragEnter($event, index)"
              @dragleave="onDragLeave($event)"
            >
              <div
                class="tj-flex tj-flex-row-between tj-padding-xs tj-text-center"
                style="width: 100%; font-size: 12px;"
              >
                <!-- 添加选择框列 -->
                <div style="width: 8%">
                  <q-checkbox v-model="item.isSelected" size="xs" />
                </div>
                <!-- 变量名列，允许拖动 -->
                <div style="width: 18%; font-size: 12px;" :draggable="true">{{ item.blm }}</div>
                <!-- 只允许第一列拖动 -->

                <!-- 其他列，禁止拖动 -->
                <div
                  style="
                    width: 18%;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                  "
                >
                  <q-select
                    outlined
                    v-model="item.bllx"
                    dense
                    options-dense
                    style="font-size: 12px"
                    :options="dataVarOptions1"
                    @virtual-scroll="changeSelect($event, index)"
                    :disable="!isEditing"
                    :readonly="!isEditing"
                  />
                </div>

                <div style="width: 18%">
                  <q-input
                    outlined
                    v-model="item.blbq"
                    dense
                    style="font-size: 12px"
                    :disable="!isEditing"
                    :readonly="!isEditing"
                  />
                </div>
                <!-- 第四列 -->
                <div
                  style="width: 18%; position: relative"
                  :id="`trigger-` + index"
                >
                  <div v-if="item.bllx === '分类型'">
                    <!-- 修改和收回按钮 -->
                    <q-btn
                      dense
                      size="sm"
                      style="font-size: 12px"
                      @click="toggleEdit(item, index)"
                      :label="item.isEditing ? '收回' : '修改'"
                      :disable="!isEditing"
                    />

                    <!-- 弹框内容使用 teleport -->
                    <teleport to="body">
                      <div
                        v-if="item.isEditing"
                        class="popover-container"
                        :style="popoverStyle"
                        @click.stop
                      >
                        <!-- 弹出框标题 -->
                        <div class="popover-header">
                          <span>变量赋值</span>
                          <q-btn
                            flat
                            round
                            dense
                            icon="close"
                            size="sm"
                            @click="toggleEdit(item, index)"
                          />
                        </div>
                        <!-- 弹出框内容 -->
                        <div class="popover-content">
                          <div class="tj-input-group">
                            <q-input
                              v-for="i in parseInt(item.blmax)"
                              :key="i"
                              :label="`变量${i}`"
                              outlined
                              dense
                              v-model="item['val' + i]"
                              :disable="!isEditing"
                              :readonly="!isEditing"
                              class="value-input"
                            />
                          </div>
                        </div>
                        <!-- 尖头 -->
                        <div class="popover-arrow"></div>
                      </div>
                    </teleport>
                  </div>
                  <div v-else>
                    <!-- 非“分类型”时显示一般的输入框 -->
                    <q-input
                      outlined
                      v-model="item.blfz"
                      dense
                      style="font-size: 12px"
                      :disable="!isEditing"
                      :readonly="!isEditing"
                    />
                  </div>
                </div>
              </div>
            </q-item>
          </q-list>
        </q-card-section>

        <!-- 添加固定在底部的按区域 -->
        <div class="fixed-bottom-buttons">
          <q-btn
            :color="isEditing ? 'primary' : 'grey'"
            :label="isEditing ? '保存' : '修改'"
            @click="toggleEditMode"
            class="q-mr-sm"
          />
          <q-btn
            v-if="isEditing"
            label="取消"
            color="negative"
            @click="cancelEdit"
          />
        </div>
      </q-card>
    </div>
  </q-page>
  <div
    v-if="visible"
    ref="doc"
    class="draggable-doc"
    :style="{
      top: position.top + 'vh',
      left: position.left + 'vw',
      width: '500px',
      height: '500px',
    }"
  >
    <!-- Header 作为不参与滚动的固定区域 -->
    <div
      class="tj-flex tj-flex-row-between tj-padding-sm tj-text-xl"
      @mousedown="startDragging"
      style="color: white; background-color: #373843"
    >
      <span>组轨建模</span>
      <button class="close-btn" @click="closeDoc">X</button>
    </div>

    <!-- 滚动内容区域 -->
    <div class="scrollable-content" style="background-color: #c6c5c5">
      <q-card class="right-card">
        <q-card-section>
          <!-- 使用新的布局容器 -->
          <div class="modeling-container">
            <!-- 左侧变量部分 -->
            <div class="variables-section">
              <!-- 唯一标识符 -->
              <div class="identifier-container">
                <div class="section-title">唯一标识符</div>
                <q-input
                  filled
                  v-model="uniqueIdentifier"
                  class="identifier-input"
                />
              </div>

              <!-- 时点变量 -->
              <div class="variable-section">
                <div class="section-title">
                  时点变量
                  <q-tooltip>时间变量与测量变量需一一对应</q-tooltip>
                </div>
                <div
                  class="variable-container"
                  @drop="onDrop('time', $event)"
                  @dragover.prevent
                >
                  <div class="variable-tags-container">
                    <div class="tags-wrapper">
                      <q-chip
                        v-for="(item, index) in timeVariable"
                        :key="index"
                        removable
                        @remove="timeVariable.splice(index, 1)"
                        class="variable-tag"
                        color="primary"
                        text-color="white"
                        size="sm"
                        dense
                      >
                        {{ item }}
                      </q-chip>
                    </div>
                    <div v-if="timeVariable.length > 0" class="variable-count">
                      共 {{ timeVariable.length }} 个变量
                    </div>
                  </div>
                </div>
              </div>

              <!-- 测量变量 -->
              <div class="variable-section">
                <div class="section-title">
                  测量变量
                  <q-tooltip>测量变量与时间变量需一一对应</q-tooltip>
                </div>
                <div
                  class="variable-container"
                  @drop="onDrop('measurement', $event)"
                  @dragover.prevent
                >
                  <div class="variable-tags-container">
                    <div class="tags-wrapper">
                      <q-chip
                        v-for="(item, index) in measurementVariable"
                        :key="index"
                        removable
                        @remove="measurementVariable.splice(index, 1)"
                        :class="[
                          'variable-tag',
                          {
                            warning:
                              timeVariable.length !==
                              measurementVariable.length,
                          },
                        ]"
                        color="primary"
                        text-color="white"
                        size="sm"
                        dense
                      >
                        {{ item }}
                      </q-chip>
                    </div>
                    <div
                      v-if="measurementVariable.length > 0"
                      class="variable-count"
                    >
                      共 {{ measurementVariable.length }} 个变量
                      <span
                        v-if="
                          timeVariable.length !== measurementVariable.length
                        "
                        class="warning-text"
                      >
                        (与时点变量数目不匹配!)
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 右侧设置部分 -->
            <div class="settings-section">
              <!-- 模型选择 -->
              <div class="setting-group">
                <div class="section-title">模型选择</div>
                <q-option-group
                  size="xs"
                  :options="mxxzOptions"
                  type="radio"
                  v-model="modelGroupSel"
                />
              </div>

              <!-- 轨迹图 -->
              <div class="setting-group">
                <div class="section-title">轨迹图</div>
                <q-option-group
                  multiple
                  size="xs"
                  :options="gjtOptions"
                  type="checkbox"
                  v-model="strjPlot"
                />
              </div>

              <!-- 输出数据集 -->
              <div class="setting-group">
                <div class="section-title">输出数据集</div>
                <div class="prefix-input">
                  前缀：<q-input filled v-model="prefix" dense />
                </div>
              </div>
            </div>
          </div>

         <!-- 组数阶数的选择 -->
         <div class="zjjmCard tj-margin-top-sm">
            <div
              class="tj-text-lg tj-padding-sm"
              style="
                background-color: #cfcfcf;
                color: #357ab6;
                font-weight: 600;
              "
            >
              轨迹组个数选择
            </div>
            <div
              class="tj-padding-sm tj-flex tj-flex-row-center tj-flex-col-center"
              style="color: #357ab6; font-weight: 600; padding-bottom: 0%"
            >
              <div class="" style="width: 20%">组数</div>
              <div class="tj-margin-left-xxl" style="width: 70%">阶数</div>
              <div class="tj-flex tj-flex-row-right" style="width: 12%">
                <div class="czan tj-text-sm" @click="resetOrders">重置</div>
              </div>
            </div>

            <!-- 动态生成输入行 -->
            <div
              class="tj-padding-sm tj-flex tj-flex-row-between tj-flex-col-center"
              v-for="(row, rowIndex) in orders"
              :key="rowIndex"
              style="padding-top: 2px; padding-bottom: 2px"
            >
              <div class="" style="width: 15%; background-color: #ffffff">
                <q-select
                  outlined
                  v-model="selectedZs[rowIndex]"
                  :options="zsOptions"
                  @change="updateColumns(rowIndex, selectedZs[rowIndex])"
                ></q-select>
              </div>

              <div
                class="tj-flex"
                style="width: 70%; flex-wrap: wrap; max-width: 70%"
              >
                <!-- 动态生成输入框列 -->
                <div
                  v-for="(col, colIndex) in row"
                  :key="colIndex"
                  style="
                    padding: 0px 2px;
                    margin: 2px;
                    background-color: #ffffff;
                    border-radius: 1px;
                    overflow: hidden;
                    width: 30px; /* 减小输入框宽度 */
                  "
                >
                  <q-input
                    borderless
                    v-model="orders[rowIndex][colIndex]"
                    style="width: 100%; margin-right: 2px; height: 25px"
                    @update:model-value="validateInput(orders[rowIndex][colIndex], rowIndex, colIndex)"
                    maxlength="1"
                  >
                    <template v-slot:before>
                      <q-tooltip>
                        只能输入0-4的数字
                      </q-tooltip>
                    </template>
                  </q-input>
                </div>
              </div>

              <!-- 加号按钮：增加行 -->
              <div
                @click="addRow"
                class="click"
                style="width: 5%; cursor: pointer"
              >
                +
              </div>
            </div>
          </div>
        </q-card-section>

        <!-- 按钮和错误信息部分 -->
        <div class="action-section">
          <div class="buttons">
            <q-btn
              label="提交"
              color="primary"
              @click="handleSubmit"
              class="q-mr-md"
            />
            <q-btn label="取消" color="secondary" @click="handleCancel" />
          </div>
          <div class="error-log">
            <div class="error-message">
              报错信息 1：某项数据为空。<br />
              报错信息 2：未选择输出参数。<br />
              报错信息 3：时间参数设置错误。
            </div>
          </div>
        </div>
      </q-card>
    </div>

    <!-- 右下角用于缩放的拖动手柄 -->
    <!-- <div class="resize-handle" @mousedown="startResizing"></div> -->
  </div>
</template>

<script setup>
import { createModel, getModel } from "src/api/api";
import {
  ref,
  onMounted,
  watch,
  reactive,
  onBeforeUnmount,
  computed,
} from "vue";
import { useQuasar } from "quasar";
import { useOperationRecordStore } from "src/stores/operation-record";
const $q = useQuasar();

// uuid一标识
const uniqueIdentifier = ref("");

// 时点变量和测量变量
const timeVariable = ref([]);
const measurementVariable = ref([]);
// 组数选择和默认值
const zsOptions = ref(["1", "2", "3", "4", "5", "6", "7", "8"]);
const selectedZs = ref(["1", "2", "3", "4", "5", "6", "7", "8"]); // 默认组数为1
const orders = ref([[""]]); // 默认1行1列

const validateInput = (value, rowIndex, colIndex) => {
  // 如果输入值不是数字，或者超出 0-4 的范围，清空输入框
  if (!/^[0-4]$/.test(value)) {
    orders.value[rowIndex][colIndex] = "";
    $q.notify({
      type: "warning",
      message: "只能输入0-4的数字",
      position: "top",
      timeout: 1500
    });
  }
};

// 根据选择的组数动态更新列数
const updateColumns = (rowIndex, Count) => {
  console.log("rowIndex", rowIndex, Count);
  const columnCount = Count;
  orders.value[rowIndex].length;

  if (orders.value[rowIndex].length < columnCount) {
    orders.value[rowIndex].push(
      ...Array(columnCount - orders.value[rowIndex].length).fill("")
    );
  } else {
    orders.value[rowIndex].length = columnCount;
  }
};

// 增加行数（点击加号）
const addRow = () => {
  const columnCount = parseInt(orders.value.length + 1, 10);
  orders.value.push(Array(columnCount).fill("")); // 加新行
};

// 重置按钮
const resetOrders = () => {
  const selectedZs = ref(["1", "2", "3", "4", "5", "6", "7", "8"]); // 默认组数为1
  orders.value = [[""]];
};

// 监听 selectedZs 中每一项的变化，只更新变化的行
selectedZs.value.forEach((_, index) => {
  watch(
    () => selectedZs.value[index], // 监听每个 rowIndex 的变化
    (newValue, oldValue) => {
      if (newValue !== oldValue) {
        updateColumns(index, newValue); // 只有当值变化时才更新行
      }
    }
  );
});

// 获取最终的 Order 数据
const getOrderData = () => {
  const data = {};
  orders.value.forEach((order, index) => {
    data[`Order${index + 1}`] = order.filter(Boolean).join(","); // 过滤空值并用逗号连接
  });
  return data;
};

const props = defineProps({
  excelData: {
    type: Array,
    required: true,
  },
  fileID: {
    type: [String, Number], // 根据实际的项目 ID 类型选择 String 或 Number
    required: true,
  },
  currentTab: {
    type: String,
    required: true,
  },
  isShowData: {
    type: Boolean,
    required: true,
  },
});

// 类型选择
const dataVarOptions1 = reactive(["连续型", "分类型", "有序性"]);
const modelGroupSel = ref(""); // 模型选择
const strjPlot = ref([]); //模型轨迹图
const prefix = ref(""); //前缀
const emit = defineEmits(["close-modeling"]);

// 模型选择
const mxxzOptions = reactive([
  {
    label: "删正态分布模型",
    value: "CNROM",
  },
]);
// 模型选择
const gjtOptions = reactive([
  {
    label: "模型轨迹图",
    value: "Model Traj Plot",
  },
  {
    label: "原始趋势图",
    value: "Raw Traj Plot",
  },
]);

// 设置默认位置和大小
const doc = ref(null);
const position = reactive({
  top: 10, // 初始 Y 位置 (vh)
  left: 50, // 初始 X 位置 (vw)
});

const size = reactive({
  width: 50, // 初始宽度 (vw)
  height: 50, // 初始高度 (vh)
});

let isDragging = false;
let isResizing = false;
let startX = 0;
let startY = 0;
let startLeft = 0;
let startTop = 0;
let startWidth = 0;
let startHeight = 0;
const visible = ref(false); // 控制文档的可见性

watch(
  () => props.currentTab,
  (newValue, oldValue) => {
    if (newValue == "modeling") {
      visible.value = true;
    } else {
      visible.value = false;
    }
  },
  {
    immediate: true,
  }
);

const onDragStart = (item, index, source) => {
  // 如果不是编辑状态，且不是拖拽到右侧建模区，则阻止拖拽
  if (!isEditing.value && source !== "remainingItems") {
    return;
  }

  isDraggingItem.value = index;

  if (!item.isSelected) {
    // 单个项目拖拽时创建拖拽预览
    const dragPreview = createDragPreview([item]);
    event.dataTransfer.setDragImage(dragPreview, 10, 10);
    event.dataTransfer.setData(
      "text/plain",
      JSON.stringify({
        items: [item],
        source,
      })
    );
  } else {
    // 多选项目拖拽时创建包含所有选中项的预览
    const selectedItems = remainingItems.value.filter(
      (item) => item.isSelected
    );
    const dragPreview = createDragPreview(selectedItems);
    event.dataTransfer.setDragImage(dragPreview, 10, 10);
    event.dataTransfer.setData(
      "text/plain",
      JSON.stringify({
        items: selectedItems,
        source,
      })
    );
  }

  event.dataTransfer.effectAllowed = "move";
};

// 添加创建拖拽预览元素的函数
const createDragPreview = (items) => {
  // 创建预览容器
  const previewContainer = document.createElement("div");
  previewContainer.style.cssText = `
    position: fixed;
    left: -1000px;
    top: -1000px;
    background: white;
    border: 1px solid #ccc;
    border-radius: 4px;
    padding: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    z-index: 9999;
    pointer-events: none;
    max-width: 300px;
  `;

  // 添加选中项目的预览
  items.forEach((item, index) => {
    const itemPreview = document.createElement("div");
    itemPreview.style.cssText = `
      padding: 4px 8px;
      margin: 2px 0;
      background: ${index === 0 ? "#e6f3ff" : "white"};
      border-radius: 2px;
      font-size: 14px;
      display: flex;
      align-items: center;
    `;
    itemPreview.textContent = item.blm;
    previewContainer.appendChild(itemPreview);
  });

  // 如果有多个项目，显示计数
  if (items.length > 1) {
    const countBadge = document.createElement("div");
    countBadge.style.cssText = `
      position: absolute;
      top: -8px;
      right: -8px;
      background: #357ab6;
      color: white;
      border-radius: 50%;
      width: 20px;
      height: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
    `;
    countBadge.textContent = items.length;
    previewContainer.appendChild(countBadge);
  }

  // 添加到文档中
  document.body.appendChild(previewContainer);

  // 在拖拽结束后清理预览元素
  setTimeout(() => {
    document.body.removeChild(previewContainer);
  }, 0);

  return previewContainer;
};

// 添加新的事件处理函数
const onDragEnd = (event) => {
  isDraggingItem.value = null;
  dragOverIndex.value = null;
  if (event.target) {
    event.target.classList.remove("dragging");
  }
};

const onDragEnter = (event, index) => {
  dragOverIndex.value = index;
  event.target.classList.add("drag-over");
};

const onDragLeave = (event) => {
  dragOverIndex.value = null;
  event.target.classList.remove("drag-over");
};

// 处理拖拽结束（放置）的逻辑
const onDrop = (key, event) => {
  const data = JSON.parse(event.dataTransfer.getData("text/plain"));
  const { items } = data;

  // 处理拖拽的多个项目
  items.forEach((item) => {
    if (key === "time") {
      // 检查是否已存在，避免重复添加
      if (!timeVariable.value.includes(item.blm)) {
        timeVariable.value.push(item.blm);
      }
    } else if (key === "measurement") {
      if (!measurementVariable.value.includes(item.blm)) {
        measurementVariable.value.push(item.blm);
      }
    }
  });

  // 拖拽完成后重置所有选择状态
  remainingItems.value.forEach((item) => {
    item.isSelected = false;
  });
};
// 监控timeVariable
watch(
  () => timeVariable.value,
  (newValue) => {
    if (newValue === "") {
      timeVariable.value = [];
    }
  }
);
watch(
  () => measurementVariable.value,
  (newValue) => {
    if (newValue === "") {
      timeVariable.value = [];
    }
  }
);

// 开始拖动的逻辑
const startDragging = (event) => {
  isDragging = true;
  const viewportWidth = window.innerWidth;
  const viewportHeight = window.innerHeight;

  // 记录初始的 left 和 top 位置
  startLeft = position.left;
  startTop = position.top;

  // 将当前鼠标点位置转化为 vw 和 vh
  startX = (event.clientX / viewportWidth) * 100 - startLeft;
  startY = (event.clientY / viewportHeight) * 100 - startTop;

  document.addEventListener("mousemove", dragging);
  document.addEventListener("mouseup", stopDragging);
};

// 拖动中的逻辑
const dragging = (event) => {
  if (isDragging) {
    const viewportWidth = window.innerWidth;
    const viewportHeight = window.innerHeight;

    // 计算新的 left 和 top
    const newLeft = (event.clientX / viewportWidth) * 100 - startX; // 计算新的 left（百分比）
    const newTop = (event.clientY / viewportHeight) * 100 - startY; // 计算新的 top（百分比）

    // 获取文档的当前高度，单位为 vh
    const docHeight = size.height; // 当前高度（vh）
    const docWidth = size.width; // 当前宽度（vw）

    // 限制 top 不能小于 10vh 且不能超过底部最大限制
    const maxTop = 100 - docHeight; // 最大 top 值，防止文档超出窗口
    position.left = Math.max(0, newLeft); // 限制 left 不能小于 0
    position.top = Math.max(0, Math.min(newTop, maxTop)); // 限制 top 在 [10, maxTop] 范围内
  }
};

// 止拖动
const stopDragging = () => {
  isDragging = false;
  document.removeEventListener("mousemove", dragging);
  document.removeEventListener("mouseup", stopDragging);
};

// 关闭文档
const closeDoc = () => {
  visible.value = false;
  emit("close-modeling");
};

// 缩放中的逻辑
const resizing = (event) => {
  if (isResizing) {
    const viewportWidth = window.innerWidth;
    const viewportHeight = window.innerHeight;

    // 计算新的宽度和高度，使用 vw 和 vh 单位
    const newWidth =
      startWidth + ((event.clientX - startX) / viewportWidth) * 100;
    const newHeight =
      startHeight + ((event.clientY - startY) / viewportHeight) * 100;

    size.width = newWidth;
    size.height = newHeight;
  }
};

// 停止缩放
const stopResizing = () => {
  isResizing = false;

  // 更新拖拽的 startX 和 startY，确保下次拖动时不会突变
  startX = 0;
  startY = 0;

  document.removeEventListener("mousemove", resizing);
  document.removeEventListener("mouseup", stopResizing);
};

onMounted(() => {
  // 组件挂载后的逻辑
});

onBeforeUnmount(() => {
  // 组件销毁前的清理逻辑
  document.removeEventListener("mousemove", dragging);
  document.removeEventListener("mouseup", stopDragging);
  document.removeEventListener("mousemove", resizing);
  document.removeEventListener("mouseup", stopResizing);
});
// ---------- 以上是拖放逻辑的代码片段 --------

const remainingItems = ref([]);

// 右侧四个收容框的定义
const containers = ref({
  time: {
    title: "时间",
    items: [],
  },
  model: {
    title: "模型",
    items: [],
  },
  measurement: {
    title: "测量",
    items: [],
  },
  output: {
    title: "输出",
    items: [],
  },
});
// 在 script setup 中添加 containerState 的定义
const containerState = ref({
  time: [],
  model: [],
  measurement: [],
  output: [],
});

// 提交时将容器状态和剩余按钮保存到localStorage中
const handleSubmit = async () => {
  // 右边表单的数据格式
// 	const	data = {
//     "ID": "Patient_id",
//     "Measure": "var1,var2,var3,var4,var5,var6,var7,var8,var9,var10,var11",
//     "Time": "t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11",
//     "Order1": "2,2",
//     "Order2": "2,2,2",
//     "Order3": "2,2,2,1",
//     "Order4": "2,2,2,2,2",
//     "Order5": "",
//     "Order6": "",
//     "Order7": "",
//     "Order8": "",
//     "Prefix": "TJCD5",
//     "Model Traj PLot": "Yes",
//     "Raw Traj Plot": "Yes",
//     "Link": "CNORM"
// }
  const data = {
    ID: uniqueIdentifier.value,
    Measure: measurementVariable.value.join(","), //格式处理
    Time: timeVariable.value.join(","),
    Order1: getOrderData().Order1,
    Order2: getOrderData().Order2,
    Order3: getOrderData().Order3,
    Order4: getOrderData().Order4,
    Order5: getOrderData().Order5,
    Order6: getOrderData().Order6,
    Order7: getOrderData().Order7,
    Order8: getOrderData().Order8,
    Prefix: prefix.value,
    "Model Traj Plot": strjPlot.value.includes("Model Traj Plot")
      ? "Yes"
      : "No", // 检查数组是否包含指定值
    "Raw Traj Plot": strjPlot.value.includes("Raw Traj Plot") ? "Yes" : "No",
    Link: modelGroupSel.value,
  };
  // 第四列提交json
  remainingItems.value.forEach((item) => {
    if (item.bllx === "分类型") {
      const values = {};
      for (let i = 1; i <= parseInt(item.blmax); i++) {
        values[`val${i}`] = item[`val${i}`] || "";
      }
      item.blfz = JSON.stringify(values);
    }
  });
  const res = await createModel({
    file_id: props.fileID,
    operation_record: data,
    result: "success",
  });
  if (res.data.code === 200) {
    $q.notify({
      message: "提交成功",
      color: "positive",
    });
  } else {
    $q.notify({
      message: "提交失败",
      color: "negative",
    });
  }
};


const operationRecordStore = useOperationRecordStore();
// 页面加载时复原状态
onMounted(async () => {
  // 检查 store 中是否已有 operation_record
  if (operationRecordStore.hasOperationRecord(props.fileID)) {
    const parsedData = operationRecordStore.getOperationRecord(props.fileID);
    remainingItems.value = parsedData.remainingItems || [...props.excelData];
    containerState.value = parsedData.containers || {
      time: [],
      model: [],
      measurement: [],
      output: [],
    };

    // 同步容器状态到 containers
    for (const key in containerState.value) {
      containers.value[key].items = [...containerState.value[key]];
    }
  } else {
    // 如果没有，则请求数据
    const res = await getModel(props.fileID);
    if (res.data.code === 200) {
      const parsedData = res.data.data.operation_record;
      // 保存到 store
      operationRecordStore.setOperationRecord(props.fileID, parsedData);
      remainingItems.value = parsedData.remainingItems || [...props.excelData];
      containerState.value = parsedData.containers || {
        time: [],
        model: [],
        measurement: [],
        output: [],
      };

      // 同步容器状态到 containers
      for (const key in containerState.value) {
        containers.value[key].items = [...containerState.value[key]];
      }
    }
  }
});

// 监视 props.fileID 的变化，重新初化状态
watch(
  () => props.fileID,
  async (newFileID) => {
    // 清理状态
    remainingItems.value = [];
    containerState.value = {
      time: [],
      model: [],
      measurement: [],
      output: [],
    };

    // 检查 store 中是否已有 operation_record
    if (operationRecordStore.hasOperationRecord(newFileID)) {
      const parsedData = operationRecordStore.getOperationRecord(newFileID);
      if (parsedData) {
        remainingItems.value = parsedData.remainingItems || [
          ...props.excelData,
        ];
        containerState.value = parsedData.containers || {
          time: [],
          model: [],
          measurement: [],
          output: [],
        };

        // 同步容器状态到 containers
        for (const key in containerState.value) {
          containers.value[key].items = [...containerState.value[key]];
        }
      } else {
        console.error("从 Store 获取的记录为空!");
      }
    } else {
      // 如果没有，则请求数据
      try {
        const res = await getModel(newFileID);

        if (res.data.code === 200) {
          const parsedData = res.data.data.operation_record;

          // 保存到 store
          operationRecordStore.setOperationRecord(newFileID, parsedData);

          remainingItems.value = parsedData.remainingItems || [
            ...props.excelData,
          ];
          containerState.value = parsedData.containers || {
            time: [],
            model: [],
            measurement: [],
            output: [],
          };

          // 同步容器状态到 containers
          for (const key in containerState.value) {
            containers.value[key].items = [...containerState.value[key]];
          }
        } else {
          // 如果获取模型失败，则重置状态
          for (const key in containers.value) {
            containers.value[key].items = [];
            containerState.value[key] = [];
          }
          remainingItems.value = [...props.excelData];
        }
      } catch (error) {
        console.error("请求数据时发生错误:", error);
      }
    }
  }
);

// 取消操作，清空localStorage并恢复初始状态
const handleCancel = () => {
  localStorage.removeItem("dragDropState");
  for (const key in containers.value) {
    containers.value[key].items = [];
    containerState.value[key] = [];
  }
  remainingItems.value = [...props.excelData];
  console.log("状态已重置");
};

// 选择数据
function changeSelect(detal, index) {
  console.log(detal, index);
  // remainingItems[index].dataVarOptions[index]
}

const toggleEdit = (item, index) => {
  // 关闭其他项的编辑状态
  remainingItems.value.forEach((otherItem, i) => {
    if (i !== index) {
      otherItem.isEditing = false;
    }
  });
  item.isEditing = !item.isEditing;
  updatePopoverPosition(item, index);
};
// 存储弹框位置样式
const popoverStyle = reactive({
  position: "fixed",
  top: "0px",
  left: "0px",
  zIndex: 1000,
  transform: 'translateY(-40%)',
});

// 更新框位置
const updatePopoverPosition = (item, index) => {
  const triggerElement = document.getElementById(`trigger-${index}`);
  if (triggerElement) {
    const rect = triggerElement.getBoundingClientRect();
    // 调整弹窗位置
    popoverStyle.top = `${rect.top + window.scrollY}px`;
    popoverStyle.left = `${rect.left + window.scrollX + rect.width + 20}px`;
  }
};

// 添加新的响应式变量
const isDraggingItem = ref(null);
const dragOverIndex = ref(null);


// 添加编辑状态控制
const isEditing = ref(false);

// 切换编辑模式
const toggleEditMode = () => {
  if (isEditing.value) {
    // 如果当前是编辑状态，点击保存
    saveChanges();
  } else {
    // 如果当前是非编辑状态，进入编辑模式
    isEditing.value = true;
  }
};

// 保存更改
const saveChanges = () => {
  // 打印当前所有内容
  console.log("当前表格数据：", remainingItems.value);

  // 显示保存成功提示
  $q.notify({
    message: "保存成功",
    color: "positive",
    position: "top",
  });

  // 退出编辑模式
  isEditing.value = false;
};

// 取消编辑
const cancelEdit = () => {
  // 提示用户确认取消
  $q.dialog({
    title: "确认取消",
    message: "确定要取消编辑吗？未保存的更改将会丢失。",
    cancel: true,
    persistent: true,
  }).onOk(() => {
    // 重置为编辑前的状态
    isEditing.value = false;
    // 关闭所有打开的修改弹窗
    remainingItems.value.forEach(item => {
      item.isEditing = false;
    });
    // 重新从 props.excelData 初始化数据
    remainingItems.value = props.excelData.map(item => ({
      ...item,
      isEditing: false,
      isSelected: false
    }));
  });
};

// 修改变量类型选择和输入框的 disabled 状态
const isInputDisabled = computed(() => !isEditing.value);

// 监听编辑状态变化
watch(isEditing, (newValue) => {
  // 可以在这里添加进入/退出编辑模式时的其他逻辑
  if (newValue) {
    $q.notify({
      message: "已进入编辑模式",
      color: "info",
      position: "top",
    });
  }
});

// 在 script setup 中添加对 isShowData 的监听
watch(
  () => props.isShowData,
  (newValue) => {
    if (newValue) {
      // 当 isShowData 变为 true 时，重新从 props.excelData 初始化数据
      if (props.excelData && props.excelData.length > 0) {
        remainingItems.value = props.excelData.map(item => ({
          ...item,
          isEditing: false,
          isSelected: false
        }));
      }
    }
  }
);

// 同时也要监听 excelData 的变化
watch(
  () => props.excelData,
  (newValue) => {
    if (newValue && newValue.length > 0) {
      remainingItems.value = newValue.map(item => ({
        ...item,
        isEditing: false,
        isSelected: false
      }));
    }
  },
  { immediate: true }  // 确保组件初始化时也执行
);

</script>

<style scoped>
.excel-content-container {
  width: 80vw;
}

.draggable-item {
  padding: 2px !important;
  min-height: 28px !important;
  border-bottom: 0.1vh solid #ccc;
  min-height: 0%;
  width: 100%;
  cursor: grab;
  transition: all 0.3s ease;
  position: relative;
}

/* 拖拽时的样式 */
.draggable-item.is-dragging {
  opacity: 0.5;
  transform: scale(0.98);
  background-color: #f0f0f0;
}

/* 拖拽经过时的样式 */
.draggable-item.drag-over {
  border-top: 2px solid #357ab6;
  padding-top: calc(1vh - 2px);
}

/* 拖拽时的动画效果 */
.dragging {
  opacity: 0.5;
  transform: scale(0.98);
  background-color: #f0f0f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 添加拖拽目标区域的动画效果 */
@keyframes pulse {
  0% {
    background-color: transparent;
  }
  50% {
    background-color: rgba(53, 122, 182, 0.1);
  }
  100% {
    background-color: transparent;
  }
}

/* 右侧拖拽目标区域的样式 */
.measurement-zone,
.time-zone {
  transition: all 0.3s ease;
  border: 2px dashed transparent;
}

.measurement-zone.drag-over,
.time-zone.drag-over {
  border-color: #357ab6;
  animation: pulse 1.5s infinite;
  background-color: rgba(53, 122, 182, 0.05);
}

/* 选中项的样式 */
.draggable-item:has(input[type="checkbox"]:checked) {
  background-color: rgba(53, 122, 182, 0.1);
}

.dropped-item {
  border: 0.1vh solid #ccc;
  margin-bottom: 1vh;
  background-color: #f5f5f5;
  min-height: 0;
}

.left-card {
  height: 80vh;
  overflow-y: auto;
  font-size: 0.7rem;
  width: 2vw;
  display: flex;
  flex-direction: column;
  max-width: 95%;
  font-size: 12px;
}

.q-card-section-customize {
  padding: 0;
  flex: 1;
  overflow-y: auto;
  /* 留出底部按钮的空间 */
  margin-bottom: 50px;
}

.fixed-bottom-buttons {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 8px;
  background-color: white;
  border-top: 1px solid #ddd;
  display: flex;
  justify-content: center;
  z-index: 2;
}

/* 当不可编辑时的样式 */
.readonly-mode {
  pointer-events: none;
  opacity: 0.7;
}

/* 可编辑元素的样式 */
.editable-element {
  pointer-events: auto;
}

.container-list {
  max-height: 28vh;
  overflow-y: auto;
}

.container-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  /* 定义两列布局 */
  gap: 10px;
  /* 每个元素之间的间距 */
}

.header-left {
  position: absolute;
  top: 1vh;
  left: 1vh;
  font-weight: bold;
  z-index: 99;
}

.header-right {
  position: absolute;
  top: 1vh;
  right: 1vh;
  z-index: 999;
  font-weight: bold;
}

.error-log {
  height: 16vh;
  border: 1px solid #e0e0e0;
  padding: 10px;
  overflow-y: auto;
  background-color: #f9f9f9;
  border-radius: 5px;
}

.error-message {
  font-size: 14px;
  color: #ff5252;
}

.draggable-doc {
  position: absolute;
  background-color: #f0f0f0;
  border: 1px solid #ccc;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  user-select: none;
  /* 允许拖动缩放 */
  overflow: hidden;
  /* 外层隐藏动，内层滚动 */
  z-index: 999;
}

/* 固定 header，使其不参与滚动 */
.header {
  background-color: #007bff;
  color: white;
  padding: 2px;
  font-size: 0.7rem;
  cursor: grab;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: sticky;
  /* 让 header 固定在顶部 */
  top: 0;
  z-index: 10;
}

.header:active {
  cursor: grabbing;
}

.close-btn {
  background-color: transparent;
  border: none;
  color: white;
  font-size: 0.7rem;
  cursor: pointer;
}

.close-btn:hover {
  color: #ff3333;
}

/* 可滚动的内容区域 */
.scrollable-content {
  height: calc(100% - 50px);
  /* 减去 header 的高度 */
  overflow-y: auto;
  /* 垂直方向滚动 */
  scroll-behavior: smooth;
  /* 平滑滚动 */
  background-color: #ffffff;
}

/* 调整容器卡片样式 */
.container-card {
  width: 100%;
  max-height: 24vh;
  min-height: 14vh;
  overflow-y: auto;
  /* 容器内的滚动 */
}

.error-log {
  height: 16vh;
  border: 1px solid #e0e0e0;
  padding: 10px;
  overflow-y: auto;
  background-color: #f9f9f9;
  border-radius: 5px;
}

.error-message {
  font-size: 14px;
  color: #ff5252;
}

/* 滚动条右下角的缩放拖动手柄 */
/* .resize-handle {
  position: absolute;
  width: 10px;
  height: 10px;
  bottom: 0;
  right: 0;
  background-color: #007bff;
  cursor: se-resize;
} */

.centered {
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.q-card-section-customize {
  padding: 0;
}

:deep .q-field__control {
  height: 35px;
  border-radius: 5px;
}

:deep .q-field__marginal {
  height: 25px;
}

:deep .q-field--auto-height .q-field__native {
  min-height: 16px;
  height: 25px;
}

:deep .q-field--auto-height .q-field__control,
.q-field--auto-height .q-field__native {
  min-height: 16px;
  height: 25px;
}

:deep .q-field--outlined .q-field__control {
  padding: 0 0 0 10px;
  width: 150px;
}

.zjjmCard {
  border-radius: 5px;
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #e5e5e5;
}

.czan {
  padding: 1px 6px;
  background-color: #ccc;
  color: #ffffff;
}

.tj-input-group {
  margin-bottom: 8px; /* 输入框之间的间距 */
  width: 100%;
}

/* 调整未聚焦时的label位置 */
.q-field--label-above .q-field__label {
  transform: translateY(-14px); /* 向上移动label */
}

/* 调整聚焦时的label位置 */
.q-field--label-above .q-field__native:focus-within ~ .q-field__label,
.q-field--label-above .q-field__prefix:focus-within ~ .q-field__label {
  transform: translateY(-4px); /* 聚焦时label向下移动 */
}
.popover-container {
  background-color: white;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border-radius: 8px;
  width: 280px;
  padding: 0;
  z-index: 1000;
  transition: all 0.2s ease-in-out;
}

.popover-header {
  background-color: #f5f5f5;
  padding: 12px 16px;
  border-radius: 8px 8px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e0e0e0;
}

.popover-header span {
  font-weight: 500;
  color: #333;
}

.popover-content {
  padding: 16px;
}

.tj-input-group {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.value-input {
  margin-bottom: 8px;
}

.value-input :deep(.q-field__control) {
  height: 36px;
}

.value-input :deep(.q-field__label) {
  font-size: 12px;
  color: #666;
}

.popover-arrow {
  position: absolute;
  left: -8px;
  top: 45%;
  transform: translateY(-50%);
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 8px 8px 8px 0;
  border-color: transparent #f5f5f5 transparent transparent;
  filter: drop-shadow(-2px 0 2px rgba(0, 0, 0, 0.1));
}

/* 添加输入框hover效果 */
.value-input:hover :deep(.q-field__control) {
  border-color: #1976d2;
}

/* 添加输入框focus效果 */
.value-input :deep(.q-field--focused .q-field__control) {
  border-color: #1976d2;
  box-shadow: 0 0 0 1px #1976d2;
}

/* 拖拽时的预览样式 */
.drag-preview {
  background: white;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  pointer-events: none;
}

.drag-preview-item {
  padding: 4px 8px;
  margin: 2px 0;
  background: #e6f3ff;
  border-radius: 2px;
}

/* 拖拽目标区域激活状态 */
.time-zone.drag-active,
.measurement-zone.drag-active {
  background-color: rgba(53, 122, 182, 0.1);
  border: 2px dashed #357ab6;
}

.variable-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.variable-container {
  position: relative;
  margin-bottom: 16px;
}

.variable-count {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.warning-text {
  color: #ff5252;
  font-weight: bold;
}

/* 当变量数量不匹配时，输入框显示警告样式 */
.variable-container:has(.warning-text) .q-input {
  border: 1px solid #ff5252;
}

.variable-input {
  width: 100%;
}

.variable-input :deep(.q-field__native) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding-right: 8px;
}

.variable-tooltip {
  max-width: 300px;
  background: #fff;
  color: #000;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.variable-list {
  max-height: 200px;
  overflow-y: auto;
}

.variable-list div {
  padding: 4px 0;
  border-bottom: 1px solid #eee;
}

.variable-list div:last-child {
  border-bottom: none;
}

/* 美化滚动条 */
.variable-list::-webkit-scrollbar {
  width: 6px;
}

.variable-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.variable-list::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

.variable-list::-webkit-scrollbar-thumb:hover {
  background: #555;
}

/* 输入框hover效果 */
.variable-input:hover :deep(.q-field__control) {
  border-color: #357ab6;
}

/* 当内容过长时显示省略号 */
.variable-input :deep(.q-field__native) {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 添加新的样式 */
.variable-input :deep(.q-field__native) {
  cursor: text;
  user-select: none; /* 防止用户选择文本 */
}

.variable-input {
  position: relative;
}

/* 当有内容时显示删除提示 */
.variable-input:hover::after {
  content: "按Delete键删除最后一项";
  position: absolute;
  bottom: -20px;
  left: 0;
  font-size: 12px;
  color: #666;
  opacity: 0.8;
}

.variable-tags-container {
  height: 120px; /* 固定高度 */
  padding: 8px;
  background: #f5f5f5;
  border-radius: 4px;
  border: 1px solid #ddd;
  display: flex;
  flex-direction: column;
}

.tags-wrapper {
  flex: 1;
  overflow-y: auto;
  padding: 4px;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  gap: 4px;
}

.variable-tag {
  margin: 2px !important;
  height: 24px !important;
  font-size: 12px !important;
}

.variable-tag :deep(.q-chip__content) {
  padding: 0 4px;
}

.variable-tag :deep(.q-chip__icon) {
  font-size: 16px;
  margin-left: 4px;
}

.variable-count {
  font-size: 11px;
  color: #666;
  padding: 4px;
  border-top: 1px solid #ddd;
  background: white;
  margin-top: auto;
}

/* 美化滚动条 */
.tags-wrapper::-webkit-scrollbar {
  width: 4px;
}

.tags-wrapper::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.tags-wrapper::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 2px;
}

.tags-wrapper::-webkit-scrollbar-thumb:hover {
  background: #999;
}

/* 空状态提示 */
.tags-wrapper:empty::before {
  content: "拖拽变量到此处";
  color: #999;
  font-size: 12px;
  padding: 8px;
  width: 100%;
  text-align: center;
}

.warning-text {
  color: #ff5252;
  font-size: 11px;
}

.modeling-container {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.variables-section {
  flex: 1;
  max-width: 45%;
}

.settings-section {
  flex: 1;
  max-width: 45%;
}

.section-title {
  color: #357ab6;
  font-weight: 600;
  font-size: 1rem;
  margin-bottom: 8px;
}

.identifier-container {
  margin-bottom: 16px;
}

.variable-section {
  margin-bottom: 16px;
}

.variable-tags-container {
  height: 100px; /* 减小高度 */
}

.setting-group {
  margin-bottom: 20px;
}

.prefix-input {
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-section {
  margin-top: 20px;
  padding: 16px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.buttons {
  display: flex;
  justify-content: center;
  margin-bottom: 16px;
}

.error-log {
  margin-top: 16px;
  max-height: 100px; /* 限制错误日志高度 */
}

/* 调整滚动区域的最大高度 */
.scrollable-content {
  max-height: calc(100vh - 100px);
  overflow-y: auto;
}

/* 优化输入框样式 */
:deep(.q-field--dense) {
  height: 32px;
}

/* 调整选项组的间距 */
:deep(.q-option-group) {
  margin-top: 4px;
}

/* 优化标签容器的滚动 */
.tags-wrapper {
  padding: 2px;
}

.variable-tag {
  margin: 1px !important;
}

/* 非编辑模式下的输入框样式 */
:deep(.q-field--disabled) {
  opacity: 1 !important; /* 保持不透明度 */
  background: #f5f5f5;
}

:deep(.q-field--disabled .q-field__native) {
  color: #666 !important; /* 保持文字颜色 */
}

/* 非编辑模式下的选择框样式 */
:deep(.q-select--disabled) {
  opacity: 1 !important;
  background: #f5f5f5;
}

/* 禁用状态下的按钮样式 */
.q-btn--disabled {
  opacity: 0.7 !important;
  cursor: not-allowed !important;
}

/* 添加非编辑模式的视觉提示 */
.readonly-indicator {
  position: absolute;
  top: 0;
  right: 0;
  background: #f5f5f5;
  padding: 2px 6px;
  border-radius: 0 4px 0 4px;
  font-size: 12px;
  color: #666;
}

/* 调整输入框和选择框的样式 */
:deep .q-field {
  min-height: 20px !important;
  width: 60px !important;  /* 减小宽度 */
}

:deep .q-field__control {
  height: 24px !important;
  min-height: 24px !important;
  padding: 0 2px !important;  /* 减小内边距 */
}

/* 修改整体卡片宽度 */
.left-card {
  width: 400px !important;  /* 减小宽度 */
  max-width: 400px !important;
}

/* 调整列宽度 */
.tj-flex > div {
  padding: 0 2px !important;
}

/* 调整变量名列的宽度 */
.draggable-item .tj-flex > div:nth-child(2) {
  width: 18% !important;
  min-width: 60px !important;
}

/* 调整其他列的宽度 */
.draggable-item .tj-flex > div:nth-child(n+3) {
  width: 18% !important;
  min-width: 60px !important;
}

/* 调整选择框列的宽度 */
.draggable-item .tj-flex > div:first-child {
  width: 8% !important;
  min-width: 30px !important;
}
</style>
